#!/bin/bash
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

# If 'google-c2d-startup-enable' metadata property is set to '0' then,
# the startup scripts are not be executed.
# The default value is '1', so the startup scripts are executed if property is not defined.
GOOGLE_C2D_STARTUP_ENABLE="$(get_attribute_value "google-c2d-startup-enable")"
GOOGLE_C2D_STARTUP_ENABLE="${GOOGLE_C2D_STARTUP_ENABLE:-1}"

readonly GOOGLE_VM_CONFIG_LOCK_FILE="/var/lock/google_vm_config.lock"

declare -i SUCCESS_CNT=0
declare -i FAILURE_CNT=0

if [[ -f "${GOOGLE_VM_CONFIG_LOCK_FILE}" ]]; then
  echo "Google C2D startup config has already run."
  echo "To run again, delete ${GOOGLE_VM_CONFIG_LOCK_FILE}"
  exit 1
fi

if [[ "${GOOGLE_C2D_STARTUP_ENABLE}" != 1 ]]; then
  echo "Google C2D startup config is disabled."
  exit 1
fi

# Run scripts in /opt/c2d/scripts and record successes/failures.
shopt -s nullglob
for script in /opt/c2d/scripts/*; do
  if [[ -x "${script}" ]]; then
    echo "--> Running: ${script}"

    # Execute startup script.
    "${script}"
    declare -i exit_code=$?

    if [[ ${exit_code} -eq 0 ]]; then
      (( SUCCESS_CNT+=1 ))
      echo "--> ${script}, exit_code=${exit_code}/SUCCESS"
    else
      (( FAILURE_CNT+=1 ))
      echo "--> ${script}, exit_code=${exit_code}/FAILURE"
    fi
  fi
done

if has_external_ip; then
  # Send status via runtime config.
  if (( ${FAILURE_CNT} > 0 )); then
    /opt/c2d/runtime-config-post-result "failure"
  else
    /opt/c2d/runtime-config-post-result "success"
  fi
fi

# Write lock file
touch "${GOOGLE_VM_CONFIG_LOCK_FILE}"
systemctl disable google-c2d-startup.service

echo "Google C2D startup config results: SUCCESSES=${SUCCESS_CNT} FAILURES=${FAILURE_CNT}"
exit ${FAILURE_CNT}
